package features.advance.leetcode.thread;

import lombok.SneakyThrows;

import java.util.concurrent.Semaphore;

/**
 *
 * 创建三个线程 一个打印a，一个打印n，一个打印t  循环交替打印antantant (编程语言不限)
 * @author LIN
 * @date 2021-04-30
 */
public class Solution1115 {

    public static void main(String[] args) throws InterruptedException {
        int n = 3;
        FooBar fooBar = new FooBar(n);

        Thread t1 = new Thread() {
            @SneakyThrows
            @Override
            public void run() {
                fooBar.foo(new Runnable() {
                    @Override
                    public void run() {
                        System.out.print("a");
                    }
                });
            }
        };

        Thread t2 = new Thread() {
            @SneakyThrows
            @Override
            public void run() {
                fooBar.bar(new Runnable() {
                    @Override
                    public void run() {
                        System.out.print("n");
                    }
                });
            }
        };
        Thread t3 = new Thread() {
            @SneakyThrows
            @Override
            public void run() {
                fooBar.ant(new Runnable() {
                    @Override
                    public void run() {
                        System.out.println("t");
                    }
                });
            }
        };
        t1.setPriority(10);
        t2.setPriority(5);
        t3.setPriority(1);
        t1.start();
        t2.start();
        t3.start();
    }



}

class FooBar {
    private int n;
    Semaphore foo = new Semaphore(1);
    Semaphore bar = new Semaphore(0);
    Semaphore ant = new Semaphore(0);


    public FooBar(int n) {
        this.n = n;
    }

    public void foo(Runnable printFoo) throws InterruptedException {

        for (int i = 0; i < n; i++) {
            foo.acquire();
//            System.out.println("A"+i);
            // printFoo.run() outputs "foo". Do not change or remove this line.
            printFoo.run();
            bar.release();
        }
    }

    public void bar(Runnable printBar) throws InterruptedException {

        for (int i = 0; i < n; i++) {
            bar.acquire();
            // printBar.run() outputs "bar". Do not change or remove this line.
//            System.out.println("B"+i);
            printBar.run();
            ant.release();
        }
    }

    public void ant(Runnable printAnt) throws InterruptedException {

        for (int i = 0; i < n; i++) {
            ant.acquire();
            // printBar.run() outputs "bar". Do not change or remove this line.
//            System.out.println("B"+i);
            printAnt.run();
            foo.release();
        }
    }
}
